//
//  HttpBaseClient.m
//  Training
//
//  Created by michael shen on 15/6/17.
//  Copyright (c) 2015年 coolem. All rights reserved.
//

#import "HttpBaseClient.h"
#define ServerBaseAddress @"http:";
#import "FileOperator.h"

@implementation HttpBaseClient

+ (HttpBaseClient *)sharedClient{
    static HttpBaseClient *httpClient = nil;
    if (httpClient == nil) {
//        httpClient = [[[self class] alloc] initWithBaseURL:[NSURL URLWithString:@"http://www.baidu.com"]];
//        [httpClient.operationQueue setMaxConcurrentOperationCount:5];
//        httpClient.requestSerializer.stringEncoding = NSUTF8StringEncoding;
//        NSMutableSet *set = [NSMutableSet setWithSet:httpClient.responseSerializer.acceptableContentTypes];
//        [set addObject:@"text/html"];
//        [set addObject:@"text/plain"];
//        httpClient.responseSerializer.acceptableContentTypes = set;
        httpClient = [[self class] manager];
        httpClient.requestSerializer.stringEncoding = NSUTF8StringEncoding;
        httpClient.requestSerializer = [AFJSONRequestSerializer serializer];
        NSMutableSet *set = [NSMutableSet setWithSet:httpClient.responseSerializer.acceptableContentTypes];
        [set addObject:@"application/json"];
        [set addObject:@"text/html"];
        [set addObject:@"text/plain"];
        [set addObject:@"multipart/form-data"];
//        [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

        [httpClient.requestSerializer setValue:@"application/json"
                         forHTTPHeaderField:@"Content-Type"];
        [httpClient.requestSerializer setValue:@"XMLHttpRequest"
                            forHTTPHeaderField:@"X-Requested-With"];
        httpClient.responseSerializer.acceptableContentTypes = set;

       
        
    }
    [httpClient.requestSerializer setValue:@"ios" forHTTPHeaderField:@"platform"];
    NSString *sidString = [[FileOperator defaultOperator] userInfoObjectForKey:@"sid"];
    if (sidString&&![sidString isEqualToString:@""]) {
        [httpClient.requestSerializer setValue:sidString forHTTPHeaderField:@"sid"];
    }
    return httpClient;
}

- (void)requestWithRequest:(NSString *)request finish:(void (^)(NSURLSessionDataTask *operation,id responseObject , NSError *error))block{
    [self GET:request parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        block(task,responseObject,nil);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        block(task,nil,error);
    }];
    
}

-(void)requestWithRequest:(NSString *)request withParameters:(id)param finish:(void (^)(NSURLSessionDataTask *,id responseObject , NSError *))block{
//    [self GET:request parameters:param success:^(AFHTTPRequestOperation *operation, id responseObject) {
//        block(operation, nil);
//    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//        block(operation, error);
//    }];
    [self POST:request parameters:param progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        block(task,responseObject,nil);

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        block(task,nil,error);

    }];
    
}

-(void)putRequestWithRequest:(NSString *)request withParameters:(id)param finish:(void (^)(NSURLSessionDataTask *,id responseObject , NSError *))block{
    //    [self GET:request parameters:param success:^(AFHTTPRequestOperation *operation, id responseObject) {
    //        block(operation, nil);
    //    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    //        block(operation, error);
    //    }];
    
    
    [self PUT:request parameters:param success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        block(task,responseObject,nil);

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        block(task,nil,error);

    }];
    
    
}

-(void)deleteRequestWithRequest:(NSString*)request withParameters:(id)param finish:(void (^)(NSURLSessionDataTask *,id responseObject , NSError *))block{
    [self DELETE:request parameters:param success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        block(task,responseObject,nil);

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        block(task,nil,error);

    }];
    


}

- (void)requestWithRequest:(NSString *)request method:(NSString *)method finish:(void (^)(NSURLSessionDataTask *operation,id responseObject, NSError *error))block {
    if ([[method uppercaseString] isEqualToString:@"GET"]) {
        [self GET:request parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            block(task,responseObject,nil);

        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            block(task,nil,error);

        }];
    } else {
        [self requestWithRequest:request finish:block];
    }
}

//- (void)uploadImageWithName:(NSString*)name withFontImage:(UIImage*)image1 withbackImage:(UIImage*)image2 block:(void (^)(id result,NSError *error)) block{
//    /*
//     此段代码如果需要修改，可以调整的位置
//     1. 把upload.php改成网站开发人员告知的地址
//     2. 把file改成网站开发人员告知的字段名
//     */
//    
//    //AFN3.0+基于封住HTPPSession的句柄
////    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//    
////    NSDictionary *dict = @{@"username":@"Saup"};
//    
//    //formData: 专门用于拼接需要上传的数据,在此位置生成一个要上传的数据体
//    NSMutableArray *imageArray = [NSMutableArray array];
//    NSDictionary *dic1 = @{@"name":@"faceView",@"ImageName":image1};
//    NSDictionary *dic2 = @{@"name":@"backView",@"ImageName":image2};
//    [imageArray addObject:dic1];
//    [imageArray addObject:dic2];
//    
//    NSString *request = [NSString stringWithFormat:@"%@%@",ServerAddress,ActionIdUpdate];
//    [self POST:request parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
//        
//        NSData *cardId = [name dataUsingEncoding:NSUTF8StringEncoding];
//        [formData appendPartWithFormData:cardId name:@"idNo"];
////        UIImage *image =[UIImage imageNamed:@"moon"];
//        for (NSDictionary *dictionary in imageArray) {
//            UIImage *image = dictionary[@"ImageName"];
//            NSData *imageData = UIImagePNGRepresentation(image);
//            // 在网络开发中，上传文件时，是文件不允许被覆盖，文件重名
//            // 要解决此问题，
//            // 可以在上传时使用当前的系统事件作为文件名
//            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//            // 设置时间格式
//            formatter.dateFormat = @"yyyyMMddHHmmss";
//            NSString *str = [formatter stringFromDate:[NSDate date]];
//            NSString *fileName = [NSString stringWithFormat:@"%@.png", str];
//            
//            double scaleNum = (double)300*1024/imageData.length;
//            NSLog(@"图片压缩率：%f",scaleNum);
//            
//            if(scaleNum <1){
//                imageData = UIImageJPEGRepresentation(image, scaleNum);
//            }else{
//                
//                imageData = UIImageJPEGRepresentation(image, 0.1);
//                
//            }
//            
//            [formData appendPartWithFileData:imageData name:dictionary[@"name"] fileName:fileName mimeType:@"image/png"];
//        }
//        
//        
//    } progress:^(NSProgress * _Nonnull uploadProgress) {
//        
//        //上传进度
//        // @property int64_t totalUnitCount;     需要下载文件的总大小
//        // @property int64_t completedUnitCount; 当前已经下载的大小
//        //
//        // 给Progress添加监听 KVO
////        NSLog(@"%f",1.0 * uploadProgress.completedUnitCount / uploadProgress.totalUnitCount);
////        // 回到主队列刷新UI,用户自定义的进度条
////        dispatch_async(dispatch_get_main_queue(), ^{
////            self.progressView.progress = 1.0 *
////            uploadProgress.completedUnitCount / uploadProgress.totalUnitCount;
////        });
//        
//    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        NSLog(@"上传成功 %@", responseObject);
//        block(responseObject,nil);
//        
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        
//        NSLog(@"上传失败 %@", error);
//        block(nil,error);
//    }];
//}


@end
